package com.xrui.hbaseview.ui;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;

/**
 * This class represents a message handler. Each class or component that want to show the user
 * some information should use this class. The information is presented in the status bar of the application.
 */
public class MessageHandler {
    private final static Logger LOG = LoggerFactory.getLogger(MessageHandler.class);

    /**
     * A list of registered listeners.
     */
    private static Collection<MessageHandlerListener> listeners;

    static {
        listeners = new ArrayList<>();
    }

    private MessageHandler() {
    }

    /**
     * This method is called by the component that wants to report an error to the user.
     *
     * @param message The error message.
     * @param ex      The exception.
     */
    public static void addError(String message, Exception ex) {
        if (message != null && !message.isEmpty()) {
            LOG.error(message, ex);
        }

        for (MessageHandlerListener listener : listeners) {
            listener.onError(message, ex);
        }
    }

    /**
     * This method is called by the component that wants to report additional information about
     * current operation to the user.
     *
     * @param message The message to report.
     */
    public static void addInfo(String message) {
        if (message != null && !message.isEmpty()) {
            message = message.replace("%", "%%");
            LOG.info(message);
        }

        for (MessageHandlerListener listener : listeners) {
            listener.onInfo(message);
        }
    }

    /**
     * This method is called by the component that wants to report to the user additional information with the option to perform
     * an action.
     *
     * @param action The action to execute if clicked.
     */
    public static void addAction(UIAction action) {
        for (MessageHandlerListener listener : listeners) {
            listener.onAction(action);
        }
    }

    /**
     * Adds a listener to the list of registered listeners.
     *
     * @param listener A listener to add.
     */
    public static void addListener(MessageHandlerListener listener) {
        listeners.add(listener);
    }

    /**
     * Removes a listener from the list of registered listeners.
     *
     * @param listener A listener to remove.
     */
    public static void removeListener(MessageHandlerListener listener) {
        listeners.remove(listener);
    }
}
